const axios = require('axios');
const config = require('../config/config');

class URLProcessor {
    static extractShareLink(text) {
        // 匹配抖音分享文本中的链接
        const urlPattern = /https?:\/\/[^\s]+/;
        const match = text.match(urlPattern);
        return match ? match[0].split(' ')[0] : null;
    }

    static async extractDouyinVideoId(shareText) {
        try {
            // 首先从分享文本中提取链接
            const shareUrl = this.extractShareLink(shareText);
            if (!shareUrl) {
                throw new Error('无法从文本中提取链接');
            }

            // 处理短链接
            let finalUrl = shareUrl;
            if (shareUrl.includes('v.douyin.com')) {
                const response = await axios.get(shareUrl, {
                    headers: config.DOUYIN.headers,
                    maxRedirects: 5
                });
                finalUrl = response.request.res.responseUrl;
            }

            // 提取视频ID的正则表达式
            const patterns = [
                /video\/(\d+)/,
                /modal_id=(\d+)/,
                /item_ids=(\d+)/,
                /\?id=(\d+)/
            ];

            for (const pattern of patterns) {
                const match = finalUrl.match(pattern);
                if (match && match[1]) {
                    return match[1];
                }
            }

            throw new Error('无法从链接中提取视频ID');
        } catch (error) {
            console.error('Error extracting video ID:', error.message);
            return null;
        }
    }
}

module.exports = URLProcessor;